package com.app.conrtoller;

import com.app.domain.ExternalResponse;
import com.app.domain.JsonResult;
import com.app.domain.UploadParameter;
import com.app.domain.YjData;
import com.app.domain.hsy.SendMessage;
import com.app.domain.ldpf.YjSingle;
import com.app.domain.wxgd.WxgdResponseResult;
import com.app.service.SendMessageService;
import com.app.service.UploadParameterService;
import com.app.service.XylcService;
import com.app.service.YjDataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 东郊质控平台通途
 */
@Slf4j
@RestController
@RequestMapping("/hukcz")
public class HukczUploadController {
    @Value("${yj.hukcz02cxlq.serviceHost}")
    private String serviceHost;
    @Value("${yj.hukcz02cxlq.source}")
    private String source;
    @Value("${yj.hukcz02cxlq.token}")
    private String token;
    @Value("${yj.hukcz02cxlq.equNum}")
    private String equNum;
    @Autowired
    YjDataService yjDataService;
    @Autowired
    UploadParameterService uploadParameterService;
    @Autowired
    XylcService uploadService;
    @Autowired
    SendMessageService sendMessageService;
    private static final String SUCCESS_STATE = "1";
    private static final String FAIL_STATE = "0";
    @RequestMapping("/findAll")
    @ResponseBody
    public JsonResult findAll(String bridgeCode, @RequestParam(value = "device_code") String device_code, String state, @RequestParam(name = "page", required = true, defaultValue = "1") Integer page, @RequestParam(name = "limit", required = true, defaultValue = "10") Integer limit) {
        return yjDataService.selectList1(bridgeCode, device_code, "",state, page, limit);

    }
    @RequestMapping("/upload")
    @ResponseBody
    public ExternalResponse upload(@RequestParam(value = "ids[]") String[] ids) throws InterruptedException {
        ExternalResponse externalResponse = null;
        try {
            int total = ids.length;
            AtomicInteger succTotal = new AtomicInteger(); // 使用AtomicInteger保证线程安全
            AtomicInteger failTotal = new AtomicInteger();
            StringBuffer responseContent = new StringBuffer();
            responseContent.append("本次共上传数据：【" + total + "】条,");
            for (String id : ids) {
                YjData yjData = yjDataService.findOne(id);
                UploadParameter uploadParameter = uploadParameterService.findOne("42");
                String uuid = sendMessageService.ConditionQuery(id);
                uploadData(yjData, uploadParameter, uuid, succTotal, failTotal, responseContent);
            }
            responseContent.append("成功【" + succTotal.get() + "】条,失败" + failTotal.get() + "条");
            externalResponse = new ExternalResponse(0, responseContent.toString(), "");
        } catch (Exception e) {
            // 对于所有捕获的异常，可以记录日志并返回一个通用的错误响应
            System.err.println("上传过程中发生异常：" + e.getMessage());
            log.error("上传过程中发生异常：" + e.getMessage(), e); // 优化异常日志记录
            externalResponse = new ExternalResponse(0, "上传过程中发生错误", "");
        }

        return externalResponse;
    }

    // 新增方法：提取上传逻辑
    private void uploadData(YjData yjData, UploadParameter uploadParameter, String uuid, AtomicInteger succTotal, AtomicInteger failTotal, StringBuffer responseContent) {
        YjSingle yjSingle = uploadService.getData(yjData, uploadParameter, uuid, equNum);
        WxgdResponseResult sqResponseResult = uploadService.sendMessage(serviceHost, yjSingle, source, token);
        log.info("上传结果：" + sqResponseResult);
        if (sqResponseResult != null && "200".equals(sqResponseResult.getCode())) {
            if(uuid==null||"".equals(uuid)){
            // 主表上传成功
            SendMessage sendMessage = new SendMessage();
            sendMessage.setSbbh(yjData.getDevice_code());
            sendMessage.setLh(yjData.getBridge_code());
            sendMessage.setKh(yjData.getDuct_code());
            sendMessage.setBusi_type("mudjack");
            sendMessage.setUpload_time(new Date());
            sendMessage.setUuid(yjSingle.getUuId());
            sendMessage.setStatus("0");
            sendMessageService.insert(sendMessage);
            }
            updateState(SUCCESS_STATE, String.valueOf(yjData.getId()));
            succTotal.incrementAndGet();
        } else {
            updateState(FAIL_STATE, String.valueOf(yjData.getId()));
            failTotal.incrementAndGet();
        }
    }

    private void updateState(String state, String id) {
        yjDataService.updateById(state, id);
    }
}